package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ApAuthorService;
import com.heima.article.service.GeneratePageService;
import com.heima.commom.exception.CustException;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojo.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.article.pojo.ApArticleConfig;
import com.heima.model.article.pojo.ApArticleContent;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojo.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ApAuthorService apAuthorService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    private GeneratePageService generatePageService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 100000)
    @Override
    public void publishArticle(Integer newsId) {
        // 1. 查询并检查自媒体文章  wmNews
        WmNews wmNews = getByWmNews(newsId);
        // 2. 封装 ApArticle
        ApArticle apArticle = getByApArticle(wmNews);
        // 3. 保存或修改 ApArticle信息
        saveOrUpdateApArticle(apArticle);
        // 4. 保存关联配置和内容信息
        saveConfigAndContent(wmNews, apArticle);
        // 5. TODO 文章页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);
        // 6. 更新 wmNews状态  改为9  并设置articleId
        updateByWmNews(wmNews, apArticle);
        // 7. TODO 通知es索引库添加文章索引
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,apArticle.getId());
        log.info("文章发布成功，并发送索引库更新通知   文章id: {}",apArticle.getId());
    }

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //参数校验
        //分页大小
        if (dto.getSize() == null && dto.getSize() <= 0) {
            dto.setSize(10);
        }
        //频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        //类型判断
        if (loadtype == null || (!ArticleConstants.LOADTYPE_LOAD_MORE.equals(loadtype) && !ArticleConstants.LOADTYPE_LOAD_NEW.equals(loadtype))) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //执行SQL语句查询
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
        //遍历给封面加前缀路径
        for (ApArticle apArticle : apArticles) {
            String images = apArticle.getImages();
            if (StringUtils.isNotBlank(images)) {
                images = Arrays.stream(images.split(","))
                        //给每个封面路径加前缀
                        .map(url -> webSite + url)
                        //拼接成字符串
                        .collect(Collectors.joining(","));
                apArticle.setImages(images);
            }
            apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
        }
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult load2(Short loadtypeLoadMore, ArticleHomeDTO dto, boolean firstPage) {
        if (firstPage) {
            String hotArticleListJson = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(hotArticleListJson)) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(hotArticleListJson, HotArticleVo.class);
                for (HotArticleVo articleVo : hotArticleVoList) {
                    String images = articleVo.getImages();
                    //给封面拼接前缀路径
                    if (StringUtils.isNotBlank(images)) {
                        images= Arrays.stream(images.split(","))
                                .map(url->webSite+url)
                                .collect(Collectors.joining(","));
                    }
                    //拼接静态页全路径
                    articleVo.setStaticUrl(readPath+articleVo.getStaticUrl());
                }
                return ResponseResult.okResult(hotArticleVoList);
            }
        }
        return this.load(loadtypeLoadMore,dto);
    }

    /**
     * 更新 wmNews状态  改为9  并设置articleId
     *
     * @param
     * @param wmNews
     * @param apArticle
     */
    private void updateByWmNews(WmNews wmNews, ApArticle apArticle) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(apArticle.getId());
        ResponseResult result = wemediaFeign.updateByStatus(wmNews);
        if (!result.checkCode()) {
            log.error("远程调用更改wmNews状态出错。");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }

    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        // 添加配置信息
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);
        // 添加文章详情
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);
    }

    /**
     * 保存或修改文章信息
     *
     * @param apArticle
     */
    private void saveOrUpdateApArticle(ApArticle apArticle) {
        // 判断wmNews之前是否关联 articleId
        if (apArticle.getId() == null) {
            // 无关联  新增 article
            // 保存文章
            //设置默认参数
            apArticle.setCollection(0); // 收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);// 评论数
            apArticle.setViews(0); // 阅读数
            this.save(apArticle);
        } else {
            // 有关联  修改 article
            // 修改文章  删除之前关联的配置信息   内容信息
            //1.id查询是否有article
            ApArticle article = this.getById(apArticle.getId());
            if (article == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "要修改的关联文章不存在");
            }
            //删除之前关联的配置信息   内容信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, article.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, article.getId()));
            this.updateById(article);
        }
    }

    /**
     * 封装 ApArticle
     *
     * @param wmNews
     * @return
     */
    private ApArticle getByApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        //拷贝
        BeanUtils.copyProperties(wmNews, apArticle);
        apArticle.setId(wmNews.getArticleId());
        apArticle.setLayout(wmNews.getType());
        //普通文章 0
        apArticle.setFlag(AdminConstants.ARTICLE_FLAG_ORDINARY);
        //远程查询频道
        ResponseResult<AdChannel> byChannel = adminFeign.getByChannel(wmNews.getChannelId());
        //判断远程查询是否成功
        if (!byChannel.checkCode()) {
            log.error("远程查询频道调用出错");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //获取频道对象
        AdChannel channel = byChannel.getData();
        if (channel == null) {
            log.error("该文章关联的频道不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该文章关联的频道不存在！！");
        }
        apArticle.setChannelName(channel.getName());
        // 设置作者信息
        if (wmNews.getUserId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "作者信息表id不存在");
        }
        ApAuthor apAuthor = apAuthorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (apAuthor == null) {
            log.error("作者信息不存在!!!");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "根据自媒体用户，查询作者信息不存在");
        }
        apArticle.setAuthorId(apAuthor.getId().longValue());
        apArticle.setAuthorName(apAuthor.getName());
        return apArticle;
    }

    /**
     * 查询并检查自媒体文章
     *
     * @param newsId
     * @return
     */
    private WmNews getByWmNews(Integer newsId) {
        //参数校验
        if (newsId == null) {
            log.error("文章id为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章id为空");
        }
        ResponseResult<WmNews> wmNewsById = wemediaFeign.findWmNewsById(newsId);
        //判断远程调用是否出错
        if (!wmNewsById.checkCode()) {
            log.error("远程调用出错");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //获取WmNews对象
        WmNews wmNews = wmNewsById.getData();
        //判断wmNews是否为空
        if (wmNews == null) {
            log.error("该文章不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该文章不存在");
        }
        //判断该文章状态是不是4 或者8
        Short status = wmNews.getStatus();
        if (!status.equals(WmNews.Status.ADMIN_SUCCESS.getCode()) && !status.equals(WmNews.Status.SUCCESS.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "该文章状态不是待发布状态");
        }
        return wmNews;
    }
}